<template>
  <div>
    <el-select v-model="currentValue" :multiple="multiple" :disabled="disabled" clearable filterable remote placeholder="请选择分类" :remote-method="remoteMethod" :loading="loading" @change="change">
      <el-option v-for="item in optionList" :key="item.id" :label="item.display_name" :value="item.id">
        <span v-if="item.level == 2">╰───</span>
        <span v-if="item.level == 3" style="margin-left:40px;">╰───</span>
        <span v-if="item.level == 4" style="margin-left:80px;">╰───</span>
        <span v-if="item.level == 5" style="margin-left:120px;">╰───</span>
        {{ item.display_name }}
      </el-option>
    </el-select>
    <!-- <el-button slot="suffix" icon="el-icon-refresh" title="刷新"></el-button> -->
  </div>
</template>

<script>
import { getCategoryListWithCache } from "@/api/business/category";

export default {
  name: "ApeCategorySelector",
  props: {
    itemType: {
      type: String,
      required: true
    },
    parentCode: {
      type: String,
      default: undefined
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String, Array],
      default: undefined
    }
  },
  data() {
    return {
      currentValue: this.value,
      items: [],
      optionList: [],
      loading: false
    };
  },
  watch: {
    value(newValue) {
      this.currentValue = newValue;
    },
    itemType(newValue) {
      this.load();
    },
    parentCode(newValue) {
      this.load();
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    change(val) {
      this.$emit("input", val);
      this.$emit("change", val);
    },
    load() {
      this.getList(this.itemType, this.parentCode);
    },
    remoteMethod(query) {
      if (query) {
        this.optionList = this.items.filter(item => {
          return (
            item.display_name.toLowerCase().indexOf(query.toLowerCase()) > -1
          );
        });
      } else {
        this.optionList = this.items;
      }
    },
    getList(itemType, parentCode) {
      this.loading = true;
      const q = {
        keywords: undefined,
        item_type: itemType,
        parent_code: parentCode,
        isOnlyRoot: undefined,
        parent_id: undefined
      };
      getCategoryListWithCache(q).then(result => {
        this.items = result;
        const rootList = q.parent_code ? this.items : this.items.filter(m => !m.parent_id);
        this.optionList = [];
        this.buildoptionList(rootList, 0);
        this.loading = false;
      });
    },
    buildoptionList(parentList, level) {
      level++
      parentList.forEach(m => {
        m.level = level
        this.optionList.push(m);
        const nodes = this.items.filter(z => z.parent_id === m.id);
        if (nodes.length > 0) {
          this.buildoptionList(nodes, level);
        }
      });
    }
  }
};
</script>
